package cn.store.web.servlet;

import cn.store.domain.Category;
import cn.store.service.serviceImp.CategoryServiceImp;
import cn.store.service.CategoryService;
import cn.store.utils.JedisUtils;
import cn.store.web.base.BaseServlet;
import net.sf.json.JSONArray;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CategoryServlet extends BaseServlet {
	
	//findAllCats:返回JSON
	public String findAllCats(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//在redis中获取全部分类信息
		Jedis jedis;
		String jsonStr;
		try {
			jedis = JedisUtils.getJedis();
			jsonStr = jedis.get("allCats");
			if (null == jsonStr || "".equals(jsonStr)) {
				//调用业务层获取全部分类
				CategoryService CategoryService = new CategoryServiceImp();
				List<Category> list = CategoryService.getAllCats();
				//将全部分类转换为JSON格式的数据
				jsonStr = JSONArray.fromObject(list).toString();
				System.out.println(jsonStr);
				//将获取到的JSON格式的数据存入redis
				jedis.set("allCats", jsonStr);
				System.out.println("redis缓存中没有数据");
			} else {
				System.out.println("redis缓存中有数据");
			}
			JedisUtils.closeJedis(jedis);
		}catch (Exception e){
			System.out.println("Redis出错");
			e.printStackTrace();
			/*正常业务不受影响*/
			CategoryService CategoryService = new CategoryServiceImp();
			List<Category> list = CategoryService.getAllCats();
			//将全部分类转换为JSON格式的数据
			jsonStr = JSONArray.fromObject(list).toString();
		}
		//将全部分类信息响应到客户端
		//告诉浏览器本次响应的数据是JSON格式的字符串
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().print(jsonStr);
		return null;
	}
	/*
	* 通过Cid查询商品类目
	* */
	public String getCatById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String cid = req.getParameter("cid");
		CategoryService categoryService=new CategoryServiceImp();
		Category category = categoryService.getCatById(cid);
		req.setAttribute("category",category);
		return "/admin/category/edit.jsp";
	}
}
